/**
 * Alipay.com Inc.
 * Copyright (c) 2009-2010 All Rights Reserved.
 */
package com.alipay.test.dbtest.script;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 
 * @author quickpoint
 * @version $Id: DDLScriptExecuter.java, v 0.1 2010-5-29 下午09:22:14 quickpoint Exp $
 */
public class DDLScriptExecuter implements ScriptExecuter {

    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(DDLScriptExecuter.class);

    private Connection          con    = null;

    public DDLScriptExecuter() {
    }

    public DDLScriptExecuter(Connection con) {
        Validate.notNull(con, "connection should not be null.");

        this.con = con;
    }

    /* (non-Javadoc)
     * @see com.alipay.test.dbtest.script.ScriptExecuter#execute(java.lang.String)
     */
    public void execute(String line) throws ScriptException {
        Validate.notNull(line, "script line should not be null.");

        if (null == con) {
            throw new ScriptException("no connection available");
        }

        doExecute(line);
    }

    private void doExecute(String line) throws ScriptException {
        System.out.println("executing: " + line);
        Statement stmt = null;
        try {
            stmt = con.createStatement();
            stmt.execute(line);
        } catch (SQLException ex) {
            logger.error("doExecute failed", ex);
            throw new ScriptException(ex);
        } finally {
            DbUtils.closeQuietly(stmt);
        }
    }

    public void setConnection(Connection con) {
        this.con = con;
    }
}
